#!/usr/bin/env python

import os
import subprocess
import socket
import sys
import time
from struct import *

import paho.mqtt.client as mqtt

if sys.version_info[0] < 3:
    expected_payload = "message"
else:
    expected_payload = b"message"


def on_message(mqttc, obj, msg):
    global run
    if msg.mid != 13423:
        print("Invalid mid ("+str(msg.mid)+")")
        exit(1)
    if msg.topic != "pub/qos2/receive":
        print("Invalid topic ("+str(msg.topic)+")")
        exit(1)
    if msg.payload != expected_payload:
        print("Invalid payload ("+str(msg.payload)+")")
        exit(1)
    if msg.qos != 2:
        print("Invalid qos ("+str(msg.qos)+")")
        exit(1)
    if msg.retain != False:
        print("Invalid retain ("+str(msg.retain)+")")
        exit(1)

    run = 0

def on_connect(mqttc, obj, flags, rc):
    if rc != 0:
        exit(rc)

run = -1
mqttc = mqtt.Client("publish-qos2-test", run)
mqttc.message_retry_set(3)
mqttc.on_connect = on_connect
mqttc.on_message = on_message

mqttc.connect("localhost", 1888)
rc = 0
while run == -1 and rc == 0:
    rc = mqttc.loop(0.3)

exit(run)
